import React from 'react'
import MarkdownIt from 'markdown-it';
// import { Marked } from 'marked'
import MdEditor, { Plugins } from 'react-markdown-editor-lite';
import { full as emoji } from 'markdown-it-emoji'
// import { markedHighlight } from "marked-highlight";
import hljs from 'highlight.js'
import xml from 'highlight.js/lib/languages/xml'
import javascript from 'highlight.js/lib/languages/javascript'
import typescript from 'highlight.js/lib/languages/typescript'
import json from 'highlight.js/lib/languages/json'
import htmlbars from 'highlight.js/lib/languages/htmlbars'
import css from 'highlight.js/lib/languages/css'
import sql from 'highlight.js/lib/languages/sql'
import { HtmlType } from 'react-markdown-editor-lite/cjs/editor/preview';
import request from '../utils/request';
import img_size_align from '../utils/img_size_align_plugin';
import 'react-markdown-editor-lite/lib/index.css';
import '../style/markdown.highlight.less'

hljs.registerLanguage('xml', xml)
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('typescript', typescript)
hljs.registerLanguage('json', json)
hljs.registerLanguage('htmlbars', htmlbars)
hljs.registerLanguage('css', css)
hljs.registerLanguage('sql', sql)

const mdParser = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value
      } catch (__) {}
    }
    return '' // use external default escaping
  }
}).use(emoji)
  .use(img_size_align) // 支持图片url调整大小和对齐，?width=300&height=300#center

// const mdParser2 = new Marked(
//   markedHighlight({
//     langPrefix: 'hljs language-',
//     highlight(code, lang, info) {
//       const language = hljs.getLanguage(lang) ? lang : 'plaintext';
//       return hljs.highlight(code, { language }).value;
//     }
//   })
// );

MdEditor.use(Plugins.TabInsert, {
  tabMapValue: 2, // note that 1 means a '\t' instead of ' '.
});

const PLUGINS = undefined;
// const PLUGINS = ['header', 'divider', 'image', 'divider', 'font-bold', 'full-screen'];

async function handleImageUpload(file: File, callback: Function) {
  const formData = new FormData()
  formData.append('file', file)
  const result = await request('/api/load', {
    method: 'POST',
    data: formData
  })
  const md5 = result.data?.data?.md5
  const imgSrc = md5 ? `/api/load/${md5}?width=50%#left` : ''
  callback(imgSrc)
}
function renderHTML(text: string) {
  let timer: number | string | NodeJS.Timeout | undefined
  // 异步渲染Markdown
  return new Promise<HtmlType>((resolve) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      const html = mdParser.render(text)
      // const html = `${mdParser2.parse(text)}`
      resolve(html)
    }, 1)
  })
}

type MarkdownEditorProps = {
  value?: string
  onChange?: Function
  readOnly?: boolean
  placeholder?: string
  name?: string
  editorInlineStyle?: object
  className?: string
  view?: {
    menu: boolean,
    md: boolean,
    html: boolean
  }
}

const MarkdownEditor: React.FC<MarkdownEditorProps> = (props) => {
  const {
    value = '', 
    onChange, 
    readOnly = false, 
    placeholder = '', 
    name = 'content',
    editorInlineStyle = { height: 500 },
    className = 'my-html-style',
    view = {
      menu: true,
      md: true,
      html: true
    }
  } = props

  function handleChange(data: { html: string, text: string }) {
    onChange && onChange(data.text)
  }
  return (
    <MdEditor 
      // id编辑器，id_md文本区域, id_html预览区域
      id='content'
      name={name}
      value={value}
      placeholder={placeholder}
      readOnly={readOnly} // 只读
      imageAccept={'.jpg,.png,.gif,.jpeg,.webp'}
      plugins={PLUGINS}
      htmlClass={`custom-html-style ${className}`}
      shortcuts={true} // 启用markdown快捷键
      style={editorInlineStyle} 
      renderHTML={renderHTML} 
      view={view}
      onChange={handleChange}
      onImageUpload={handleImageUpload}
    />
  )
}

export default MarkdownEditor